package com.schezhi.link.auth.session;


import com.auth0.jwt.JWT;
import com.c39.cloud.rbac.model.auth.AuthStaffVO;
import com.cqfan.cloud.framework.jwt.component.JwtComponent;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: JiaLing.Fan
 * @Date: 2022/11/30 21:20
 * @Description:
 */
@Component
public class LocalSessionTemplate implements SessionTemplate<AuthStaffVO> {

    private Map<String, AuthStaffVO> properties = new ConcurrentHashMap<>();

    private ThreadLocal<String> threadLocal = new ThreadLocal<String>();


    @Resource
    private JwtComponent jwtComponent;


    @Override
    public AuthStaffVO get() {
        String value = this.threadLocal.get();
        return get(value);
    }

    @Override
    public AuthStaffVO get(String sessionId) {
        String signature = JWT.decode(sessionId).getSignature();
        this.threadLocal.set(sessionId);
        AuthStaffVO authStaffVO = properties.get(signature);
        try {
            jwtComponent.verifyToken(sessionId , authStaffVO.getStaffNumber());
        } catch (Exception e) {
            e.printStackTrace();
             return null;
        }
        return authStaffVO;
    }


    @Override
    public AuthStaffVO getSign(String sessionId) {
        return get(sessionId);
    }


    @Override
    public void put(String sessionId, AuthStaffVO data) {
        this.properties.put(sessionId, data);
    }

    @Override
    public void putSign(String sessionId, AuthStaffVO data) {
        String signature = JWT.decode(sessionId).getSignature();
        this.properties.put(signature, data);
    }

    @Override
    public void putSign(String sessionId, AuthStaffVO data, int expires) {

    }

    @Override
    public void remove(String sessionId) {
        this.properties.remove(sessionId);
    }

    @Override
    public Map<String, AuthStaffVO> gets() {
        return this.properties;
    }

    @Override
    public void removes() {
        this.properties.clear();
    }

    @Override
    public void currentThreadremove() {
        this.threadLocal.remove();
    }


}
